{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ee194690",
   "metadata": {},
   "outputs": [],
   "source": [
    "deployment = \"gpt4\"\n",
    "model = \"gpt-4\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de6a55d2",
   "metadata": {},
   "source": [
    "# 回顾"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6a4415ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "def analyze_user_review(text):\n",
    "    messages = []\n",
    "    messages.append( {\"role\": \"system\", \n",
    "                      \"content\": \"\"\"\n",
    "                      You are an assistant. \n",
    "                      Please, analyze the user reviews according to the following instruction: \n",
    "                      If the review is postive, you should output 'Y', otherwise output 'N'\n",
    "                      \"\"\"})\n",
    "    messages.append( {\"role\": \"user\", \"content\": text})\n",
    "    response = openai.ChatCompletion.create(\n",
    "        engine=deployment, \n",
    "        messages=messages,\n",
    "        temperature=0.5,\n",
    "        max_tokens = 100\n",
    "    )\n",
    "    return response[\"choices\"][0][\"message\"][\"content\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "56058099",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Y'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "analyze_user_review(\"服务热情周到。\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9a5473f9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'N'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "analyze_user_review(\"不理不睬。\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "017882d2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'N'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "analyze_user_review(\"用餐环境差，等待时间长。\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "7537df8a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: langchain in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (0.0.285)\n",
      "Requirement already satisfied: PyYAML>=5.3 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (6.0)\n",
      "Requirement already satisfied: SQLAlchemy<3,>=1.4 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (1.4.39)\n",
      "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (3.8.3)\n",
      "Requirement already satisfied: dataclasses-json<0.6.0,>=0.5.7 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (0.5.14)\n",
      "Requirement already satisfied: langsmith<0.1.0,>=0.0.21 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (0.0.26)\n",
      "Requirement already satisfied: numexpr<3.0.0,>=2.8.4 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (2.8.4)\n",
      "Requirement already satisfied: numpy<2,>=1 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (1.24.3)\n",
      "Requirement already satisfied: pydantic<3,>=1 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (1.10.12)\n",
      "Requirement already satisfied: requests<3,>=2 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (2.31.0)\n",
      "Requirement already satisfied: tenacity<9.0.0,>=8.1.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from langchain) (8.2.2)\n",
      "Requirement already satisfied: attrs>=17.3.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (22.1.0)\n",
      "Requirement already satisfied: charset-normalizer<3.0,>=2.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (2.0.4)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (6.0.2)\n",
      "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (4.0.2)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.8.1)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.3.3)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.2.0)\n",
      "Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from dataclasses-json<0.6.0,>=0.5.7->langchain) (3.20.1)\n",
      "Requirement already satisfied: typing-inspect<1,>=0.4.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from dataclasses-json<0.6.0,>=0.5.7->langchain) (0.9.0)\n",
      "Requirement already satisfied: typing-extensions>=4.2.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from pydantic<3,>=1->langchain) (4.7.1)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from requests<3,>=2->langchain) (3.4)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from requests<3,>=2->langchain) (1.26.16)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from requests<3,>=2->langchain) (2023.7.22)\n",
      "Requirement already satisfied: packaging>=17.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from marshmallow<4.0.0,>=3.18.0->dataclasses-json<0.6.0,>=0.5.7->langchain) (23.0)\n",
      "Requirement already satisfied: mypy-extensions>=0.3.0 in /Users/mbj0593/anaconda3/lib/python3.11/site-packages (from typing-inspect<1,>=0.4.0->dataclasses-json<0.6.0,>=0.5.7->langchain) (0.4.3)\n"
     ]
    }
   ],
   "source": [
    "!pip install langchain==0.0.338"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e1d51c9",
   "metadata": {},
   "source": [
    "# 提示词模版"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a9749461",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Spectrum Socks'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain import PromptTemplate, OpenAI, LLMChain\n",
    "\n",
    "from langchain.chat_models import AzureChatOpenAI\n",
    "# from langchain.chat_models import ChatOpenAI #直接访问OpenAI的GPT服务\n",
    "\n",
    "prompt_template = \"What is a good name for a company that makes {product}? And only return the best one.\"\n",
    "\n",
    "#llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0) #直接访问OpenAI的GPT服务\n",
    "llm = AzureChatOpenAI(deployment_name = deployment, model_name=model, temperature=0, max_tokens=200) # 通过Azure的OpenAI服务\n",
    "llm_chain = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=PromptTemplate.from_template(prompt_template)\n",
    ")\n",
    "llm_chain.run(\"colorful socks\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3e5f2fbf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'text': 'SkyOps Innovations'},\n",
       " {'text': 'Silent Symphony'},\n",
       " {'text': 'Spectrum Socks'}]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "products = [{\"product\":\"'cloudnative devops platform'\"},\n",
    "            {\"product\":\"'Noise cancellation headphone'\"}, \n",
    "            {\"product\":\"colorful socks\"}]\n",
    "llm_chain.apply(products)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9edff0fc",
   "metadata": {},
   "source": [
    "# API调用链\n",
    "## HTTP request chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7125db24",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import PromptTemplate, OpenAI, LLMChain\n",
    "from langchain.chains import LLMRequestsChain\n",
    "from langchain.chat_models import AzureChatOpenAI\n",
    "# from langchain.chat_models import ChatOpenAI #直接访问OpenAI的GPT服务\n",
    "\n",
    "#llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0) #直接访问OpenAI的GPT服务\n",
    "llm = AzureChatOpenAI(deployment_name = deployment, model_name=model, temperature=0, max_tokens=200) #通过Azure的OpenAI服务\n",
    "\n",
    "def query_baidu(question):\n",
    "      template = \"\"\"Between >>> and <<< are the raw search result text from web.\n",
    "      Extract the answer to the question '{query}' or say \"not found\" if the information is not contained.\n",
    "      Use the format\n",
    "      Extracted:<answer or \"not found\">\n",
    "      >>> {requests_result} <<<\n",
    "      Extracted:\"\"\"\n",
    "\n",
    "      PROMPT = PromptTemplate(\n",
    "          input_variables=[\"query\", \"requests_result\"],\n",
    "          template=template,\n",
    "      )\n",
    "\n",
    "      inputs = {\n",
    "          \"query\": question,\n",
    "          \"url\": \"http://www.baidu.com/s?wd=\" + question.replace(\" \", \"+\")\n",
    "      }\n",
    "      requests_chain = LLMRequestsChain(llm_chain = LLMChain(llm=llm, prompt=PROMPT), output_key=\"query_info\", verbose=True)\n",
    "      res = requests_chain.run(inputs)\n",
    "      return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "39ac85a9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMRequestsChain chain...\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'23°晴东南风1级20~26°C'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "query_baidu(\"今天北京天气？\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "9ca99892",
   "metadata": {},
   "outputs": [],
   "source": [
    "# import os\n",
    "# os.environ[\"SERPER_API_KEY\"] = \"\"\n",
    "# https://serper.dev\n",
    "from langchain.utilities import GoogleSerperAPIWrapper\n",
    "def query_web(question):\n",
    "    search = GoogleSerperAPIWrapper()\n",
    "    return search.run(question)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "681ec2dc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'72°F'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "query_web(\"今天北京天气？\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36ed7650",
   "metadata": {},
   "source": [
    "# 调用链"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "073cc55c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import PromptTemplate, OpenAI, LLMChain\n",
    "from langchain.chat_models import AzureChatOpenAI\n",
    "from langchain.chains import SequentialChain\n",
    "from langchain.chat_models import AzureChatOpenAI\n",
    "# from langchain.chat_models import ChatOpenAI #直接访问OpenAI的GPT服务\n",
    "\n",
    "#llm = ChatOpenAI(model_name=\"gpt-4\", temperature=0) #直接访问OpenAI的GPT服务\n",
    "llm = AzureChatOpenAI(deployment_name = deployment, model_name=model, temperature=0, max_tokens=200)\n",
    "\n",
    "summarizing_prompt_template = \"\"\"\n",
    "Summarize the following content into a sentence less than 20 words:\n",
    "---\n",
    "{content}\n",
    "\n",
    "\"\"\"\n",
    "summarizing_chain = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=PromptTemplate.from_template(summarizing_prompt_template),\n",
    "    output_key = \"summary\"\n",
    ")\n",
    "\n",
    "translating_prompt_template = \"\"\"\n",
    "translate \"{summary}\" into Chinese:\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "translating_chain = LLMChain(\n",
    "    llm = llm,\n",
    "    prompt=PromptTemplate.from_template(translating_prompt_template),\n",
    "    output_key = \"translated\"\n",
    ")\n",
    "\n",
    "overall_chain = SequentialChain(\n",
    "    chains=[summarizing_chain, translating_chain],\n",
    "    input_variables=[\"content\"],\n",
    "    output_variables=[ \"summary\",\"translated\"],\n",
    "    verbose=True\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "778d79d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new SequentialChain chain...\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "summary:LangChain is a framework for creating applications powered by language models, offering data-aware and agentic features, modular components, and pre-assembled chains for specific tasks.\n",
      "中文:\"LangChain是一个用于创建由语言模型驱动的应用程序的框架，提供数据感知和代理特性，模块化组件，以及针对特定任务的预组装链条。\"\n"
     ]
    }
   ],
   "source": [
    "res = overall_chain(\"\"\"\n",
    "LangChain is a framework for developing applications powered by language models. It enables applications that are:\n",
    "\n",
    "Data-aware: connect a language model to other sources of data\n",
    "Agentic: allow a language model to interact with its environment\n",
    "The main value props of LangChain are:\n",
    "\n",
    "Components: abstractions for working with language models, along with a collection of implementations for each abstraction. Components are modular and easy-to-use, whether you are using the rest of the LangChain framework or not\n",
    "Off-the-shelf chains: a structured assembly of components for accomplishing specific higher-level tasks\n",
    "Off-the-shelf chains make it easy to get started. For more complex applications and nuanced use-cases, components make it easy to customize existing chains or build new ones.\n",
    "\"\"\")\n",
    "\n",
    "print(\"summary:\"+res[\"summary\"])\n",
    "\n",
    "print(\"中文:\"+res[\"translated\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b00c5ce",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
